package br.com.usjt.sge.correios;

import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.Session;

public class CepDAOHibernate implements CepDAO {

	private static final Logger logger = Logger.getLogger(CepDAOHibernate.class
			.getName());
	private Session session;

	public void setSession(Session session) {

		this.session = session;

	}

	@Override
	public Cep buscaCep(Long cep) {

		try {

			logger.info("Localizando cep  na base de dados.");
			return (Cep) this.session.get(Cep.class, cep);

		} catch (Exception e) {

			logger.error("Erro na busca do cep - " + e.getMessage());
			throw new ExceptionInInitializerError();

		}

	}

	@Override
	public Cep consultaCep(String cep) {

		try {

			String hql = "select c from Cep c where c.cep = :cep";
			Query consulta = this.session.createQuery(hql);
			consulta.setString("cep", cep);

			logger.info("Consultando cep  na base de dados.");
			return (Cep) consulta.uniqueResult();

		} catch (Exception e) {

			logger.error("Erro na consulta de cep : " + e.getMessage());
			throw new ExceptionInInitializerError();

		}

	}

}
